package yf.mall.controller;


import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yf.annotation.LoginUserId;
import com.yf.consts.DaoConst;
import com.yf.controller.SysUserController;
import com.yf.entity.SysUserEntity;
import com.yf.response.RRException;
import com.yf.service.SysRoleService;
import com.yf.service.SysUserRoleService;
import com.yf.service.SysUserService;
import com.yf.utils.ShiroUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import yf.mall.entity.ShopEntity;
import yf.mall.entity.SysUsersEntity;
import yf.mall.entity.UserEntity;
import yf.mall.service.ShopService;
import yf.mall.service.SysUsersService;
import com.yf.response.R;
import yf.mall.service.UserService;

import java.util.Date;
import java.util.List;
import java.util.Map;


/**
 * 系统用户Controller
 *
 * @author que
 * @email 505860922@qq.com
 * @date Sun Jun 28 17:37:34 CST 2020
 */
@RestController
@RequestMapping("/sys/users")
public class SysUsersController {
    @Autowired
    private SysUsersService sysUserService;
    @Autowired
    private UserService userService;
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    SysUserRoleService sysUserRoleService;
    @Autowired
    ShopService shopService;

    /**
     * 列表系统用户
     */
    @RequestMapping("/list")
    public R list(@RequestParam Map<String,Object> params) {
        PageHelper.startPage(DaoConst.getPage(params),DaoConst.getLIMIT(params));
        List<SysUsersEntity> sysUserList= null;
        //根据店铺查找
        if (params.get("shopName") != null && !"".equals(params.get("shopName"))){
            String shopName = (String)params.get("shopName");
            String username = null;
            String mobile = null;
            Integer status = null;
            if (params.get("username") != null && !"".equals(params.get("username"))){
                username = (String)params.get("username");
            }
            if (params.get("status") != null && !"".equals(params.get("status"))){
                status = Integer.parseInt((String) params.get("status")) ;
            }
            if (params.get("mobile") != null && !"".equals(params.get("mobile"))){
                mobile = (String)params.get("mobile");
            }
            sysUserList = sysUserService.findByShopName(shopName, status, username, mobile);
        }else {
            sysUserList = sysUserService.queryList(params);
        }
        //获取用户编码
        if (sysUserList != null && sysUserList.size() > 0){
            for (SysUsersEntity sysUsersEntity : sysUserList) {
                Long userId = sysUserService.findBySysUserId(sysUsersEntity.getUserId());
                if (userId != null){
                    sysUsersEntity.setUserCode(userService.get(userId).getCode());
                    ShopEntity shopEntity = shopService.findByUserId(userId);
                    if (shopEntity != null){
                        sysUsersEntity.setShopName(shopEntity.getName());
                    }
                }
            }
        }
        return R.ok(new PageInfo(sysUserList));
    }

    /**
     * 查看系统用户
     */
    @RequestMapping("/info/{userId}")
    public R info(@PathVariable("userId") Long userId) {
        SysUsersEntity sysUser = sysUserService.get(userId);
        List<Long> roleIdList = this.sysUserRoleService.queryRoleIdList(userId);
        sysUser.setRoleIdList(roleIdList);
        //获取用户编号
        Long id = sysUserService.findBySysUserId(sysUser.getUserId());
        if (id != null){
            UserEntity userEntity = userService.get(id);
            sysUser.setUserCode(userEntity.getCode());
        }
        Long shopUserId = sysUserService.findBySysUserId(userId);
        ShopEntity shopEntity = shopService.findByUserId(shopUserId);
        if (shopEntity != null){
            sysUser.setShopName(shopEntity.getName());
        }
        return R.ok(sysUser);
    }
    /**
     * 保存系统用户
     */
    @RequestMapping("/save")
    @Transactional(rollbackFor = Exception.class)
    public R save(SysUsersEntity sysUser) {

        sysUser.setCreateUserId(ShiroUtils.getUserId());
        sysUser.setCreateTime(new Date());
        //密码加密
        if (StringUtils.isBlank(sysUser.getPassword())) {
            sysUser.setPassword((new Sha256Hash("888888")).toHex());
        } else {
            sysUser.setPassword((new Sha256Hash(sysUser.getPassword())).toHex());
        }

        this.sysUserService.save(sysUser);
//        this.checkRole(sysUser);
        this.sysUserRoleService.saveOrUpdate(sysUser.getUserId(), sysUser.getRoleIdList());

        if (sysUser.getUserCode() != null && !"".equals(sysUser.getUserCode())){
            UserEntity userEntity = userService.findByCode(sysUser.getUserCode());
            if (userEntity == null){
                throw  new RRException("用户编号不存在");
            }
            sysUserService.saveUserIdAndSysUserId(sysUser.getUserId(),userEntity.getId());
        }

        return R.ok(sysUser);
    }
    private void checkRole(SysUsersEntity user) {
        if (user.getCreateUserId()!=null&&user.getCreateUserId() != 1L) {
            List<Long> roleIdList = this.sysUserRoleService.queryRoleIdList(user.getCreateUserId());
            if (!roleIdList.containsAll(user.getRoleIdList())) {
                throw new RRException("新增用户所选角色，不是本人创建");
            }
        }
    }
    /**
     * 修改系统用户
     */
    @RequestMapping("/update")
    @Transactional(rollbackFor = Exception.class)
    public R update(SysUsersEntity sysUser) {
        if (!StringUtils.isBlank(sysUser.getPassword())) {
            sysUser.setPassword((new Sha256Hash(sysUser.getPassword())).toHex());
        }
        sysUserService.update(sysUser);
        this.checkRole(sysUser);
        this.sysUserRoleService.saveOrUpdate(sysUser.getUserId(), sysUser.getRoleIdList());

        saveOrUpdate(sysUser); //操作中间表
        return R.ok(sysUser);
    }

    private void saveOrUpdate(SysUsersEntity sysUser) {
        if (sysUser.getUserCode()!= null && !"".equals(sysUser.getUserCode())){
            //获取用户
            UserEntity userEntity = userService.findByCode(sysUser.getUserCode());
            if (userEntity == null){
                throw  new RRException("用户编号不存在");
            }
            //获取中间表有没有存在绑定用户
            Long number = sysUserService.findBySysUserId(sysUser.getUserId());
            if (number == null){
                //没有 直接添加
                sysUserService.saveUserIdAndSysUserId(sysUser.getUserId(),userEntity.getId());
            }else {
                //修改
                sysUserService.updateBySysUserId(sysUser.getUserId(),userEntity.getId());
            }
        }else {
            //用户编号为空  获取中间表存不存在数据  存在则删除
            Long userId = sysUserService.findBySysUserId(sysUser.getUserId());
            if (userId != null){
                sysUserService.delBySysUserId(sysUser.getUserId());
            }
        }
    }

    /**
     * 删除系统用户
     */
    @RequestMapping("/delete")
    @Transactional(rollbackFor = Exception.class)
    public R delete(Long[] ids) {
        sysUserService.deleteBatch(ids);
        for (Long id : ids) {
            sysUserService.delBySysUserId(id);
        }
        return R.ok();
    }

    /**
    @ModelAttribute
    public SearchParam<SysUserEntity> searchParam(SearchParam<SysUserEntity> params, SysUserEntity sysUser) {
        if (sysUser != null) {
            params.setEntity(sysUser);
        }

        return params;
    }
 **/
    /***********自定义开始***********/
}
